"""
应用管理API端点
"""
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.models.application import Application
from app.models.user import User
from app.schemas.application import Application as ApplicationSchema, ApplicationCreate, ApplicationUpdate
from app.api.endpoints.auth import get_current_user

router = APIRouter()


@router.get("/", response_model=List[ApplicationSchema])
async def get_applications(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """获取应用列表"""
    applications = db.query(Application).offset(skip).limit(limit).all()
    return applications


@router.get("/{app_id}", response_model=ApplicationSchema)
async def get_application(
    app_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """获取应用详情"""
    application = db.query(Application).filter(Application.id == app_id).first()
    if not application:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="应用不存在"
        )
    return application


@router.post("/", response_model=ApplicationSchema)
async def create_application(
    app_in: ApplicationCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """创建应用"""
    # 检查应用名是否已存在
    if db.query(Application).filter(Application.name == app_in.name).first():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="应用名已存在"
        )
    
    # 创建应用
    application = Application(**app_in.dict())
    db.add(application)
    db.commit()
    db.refresh(application)
    
    return application


@router.put("/{app_id}", response_model=ApplicationSchema)
async def update_application(
    app_id: int,
    app_in: ApplicationUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """更新应用"""
    application = db.query(Application).filter(Application.id == app_id).first()
    if not application:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="应用不存在"
        )
    
    # 更新应用信息
    update_data = app_in.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(application, field, value)
    
    db.commit()
    db.refresh(application)
    
    return application


@router.delete("/{app_id}")
async def delete_application(
    app_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """删除应用"""
    application = db.query(Application).filter(Application.id == app_id).first()
    if not application:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="应用不存在"
        )
    
    # 软删除（禁用应用）
    application.is_active = False
    db.commit()
    
    return {"message": "应用已删除"}


@router.post("/{app_id}/build")
async def build_application(
    app_id: int,
    version: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """构建应用"""
    application = db.query(Application).filter(Application.id == app_id).first()
    if not application:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="应用不存在"
        )
    
    # TODO: 实现构建逻辑
    return {"message": f"开始构建应用 {application.name} 版本 {version}"}


@router.get("/{app_id}/versions")
async def get_application_versions(
    app_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
) -> Any:
    """获取应用版本列表"""
    application = db.query(Application).filter(Application.id == app_id).first()
    if not application:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="应用不存在"
        )
    
    # TODO: 实现版本列表获取逻辑
    return {"versions": []}
